package com.xzy.jooq.learn.test;

import com.xzy.jooq.learn.codegen.tables.records.LjUserRecord;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

import static com.xzy.jooq.learn.codegen.tables.LjUser.LJ_USER;

/**
 * 基础查询操作
 *
 * @author xzy.xiao
 * @date 2022/6/27  13:40
 */
public class Main {

    private static final String JDBC_URL = "jdbc:mysql://127.0.0.1:3306/learn_jooq?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false";
    private static final String JDBC_USERNAME = "root";
    private static final String JDBC_PASSWORD = "123456";

    public static void main(String[] args) {

        // 1.获取数据库连接
        try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD)) {

            // 2.获取 JOOQ 执行器
            DSLContext dslContext = DSL.using(connection, SQLDialect.MYSQL);

            // 3.查询数据
            Result<Record> rawRecords = dslContext.select().from(LJ_USER).fetch();

            // <A> Result 实现了 List 接口
            rawRecords.forEach(
                    rawRecord -> {
                        Integer id = rawRecord.getValue(LJ_USER.ID);
                        String realName = rawRecord.getValue(LJ_USER.REAL_NAME);
                        System.out.printf("id：%d realName：%s\n", id, realName);
                    }
            );

            // <B> 可以通过 Record.into 方法将默认的 Record 对象转换为指定表的 Record 对象
            rawRecords.forEach(
                    rawRecord -> {
                        LjUserRecord user = rawRecord.into(LJ_USER);
                        Integer id = user.getId();
                        String realName = user.getRealName();
                        System.out.printf("id：%d realName：%s\n", id, realName);
                    }
            );

            // <C> 也可以通过 Result.into 方法将默认的 Record 对象转换为指定表的 Record 对象
            Result<LjUserRecord> userRecords = rawRecords.into(LJ_USER);
            userRecords.forEach(user -> {
                Integer id = user.getId();
                String realName = user.getRealName();
                System.out.printf("id：%d realName：%s\n", id, realName);
            });

            // <D> 可以使用 fetchInto 方法直接指定 Record 类型
            Result<LjUserRecord> userRecords2 = dslContext.select().from(LJ_USER).fetchInto(LJ_USER);
            List<LjUserRecord> userRecordList = dslContext.select().from(LJ_USER).fetchInto(LjUserRecord.class);
            System.out.println(userRecords2);
            System.out.println(userRecordList);

        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
